package com.study;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        //获取连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置连接参数
        connectionFactory.setUri("amqp://root:123456@192.168.181.131:5672/%2f");
        //amqp://amqp://root:123456@192.168.181.131:5672/%2f

        //获取连接对象
        Connection connection = connectionFactory.newConnection();

        //获取channel信道
        Channel channel = connection.createChannel();


        //将该信道设置为生产者消息确认信道
        AMQP.Confirm.SelectOk selectOk = channel.confirmSelect();

        /*
        * 并声明消息队列名称，是否持久化，是否可自动删除等信息
        * */
        channel.queueDeclare("queue.x",true,false,false,null);


        //通过信道对象声明交换器
        /*
        * 并制定交换器名称，以及交换机类型等信息
        * */
        channel.exchangeDeclare("exchange.x1","direct",true,false,null);


        //将消息队列与交换机进行绑定
        channel.queueBind("queue.x","exchange.x1","routingkey.x");


        String message = "hello.world";

        //发送消息并同步等待rabbitmq确认消息
        try{
            channel.waitForConfirms(5000);
            channel.basicPublish("exchange.x1","routingkey.x",null,message.getBytes());
            System.out.println("消息被确认：message = " + message);
        } catch (IOException e) {
            e.printStackTrace(); System.err.println("消息被拒绝！ message = " + message);
        } catch (InterruptedException e) {
            e.printStackTrace(); System.err.println("在不是Publisher Confirms的通道上使用该方法");
        } catch (TimeoutException e) {
            e.printStackTrace(); System.err.println("等待消息确认超时！ message = " + message); }


        channel.close();
        connection.close();
    }
}
